<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-warn"></i>&nbsp;&nbsp;一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <div class="container">
            <div class="table_btn">
                <el-button  icon="el-icon-refresh" @click="refresh"  :loading="refreshLoading">刷新</el-button>
                <el-button type="success" icon="el-icon-lx-roundadd" @click="addVisible = true">添加</el-button>
                <el-button type="danger" icon="el-icon-delete"  @click="allDelete()">批量删除</el-button>
            </div>

            <!--列表-->
            <div class="box_table">
                <el-table
                        :data="treeList"
                        style="width: 100%;margin-bottom: 20px;"
                        row-key="id"
                        border
                        default-expand-all
                        @selection-change="handleSelectionChange"
                        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                    <el-table-column
                            el-table-column
                            type="selection"
                            width="50">
                    </el-table-column>

                    <el-table-column
                            prop="name"
                            label="名称">
                    </el-table-column>
                    <el-table-column
                            prop="id"
                            label="ID"
                            width="100">
                    </el-table-column>
                    <el-table-column
                            prop="parent_id"
                            label="父级"
                            width="100">
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            label="状态"
                            width="100">
                        <template slot-scope="scope">
                            <el-tag
                                    :type="scope.row.status === 1 ? 'success' : 'danger'"
                                    disable-transitions>{{scope.row.status === 1 ? "正常" : "禁用"}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作"  width="200">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    icon="el-icon-edit"
                                    type="primary"
                                    @click="handleEdit(scope.$index, scope.row)">
                                编辑
                            </el-button>
                            <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.$index, scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <!-- 新增角色 -->
        <el-dialog title="添加用户组" :visible.sync="addVisible" width="40%">
            <el-form ref="form" :model="form" :rules="addRules" label-width="70px">

                <el-form-item label="父级"  prop="parent_id">

                    <el-select v-model="form.parent_id" size="medium" placeholder="请选择" >
                        <el-option
                                v-for="item in groupOptions"
                                :key="item.id"
                                :label="item.title_show"
                                :value="item.id">
                        </el-option>
                    </el-select>

                </el-form-item>

                <el-form-item label="排序" prop="list_order">
                    <el-input type="number"  v-model="form.list_order" ></el-input>
                </el-form-item>

                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称" ></el-input>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input  type="textarea"
                               placeholder="请输入备注"
                               :rows="2"
                               v-model="form.remark">
                    </el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="form.status"
                               active-text="正常"
                               inactive-text="隐藏"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>

                <el-form-item label="权限" prop="rule">
                    <el-tree
                        ref="add-auth-tree"
                        :data="auth"
                        show-checkbox
                        :props="{label:'title'}"
                        node-key="id"
                        @check-change="handleAddAuthCheckChange">
                    </el-tree>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="add('form')"  :loading="addLoading" >确 定</el-button>
            </span>
        </el-dialog>

        <!--编辑角色-->
        <el-dialog title="编辑用户组" :visible.sync="editDialog" width="40%">
            <el-form ref="edit-form" :model="currentEditData" :rules="addRules" label-width="70px">

                <el-form-item label="父级"  prop="parent_id">

                    <el-select v-model="currentEditData.parent_id" size="medium" placeholder="请选择" >
                        <el-option
                                v-for="item in groupOptions"
                                :key="item.id"
                                :label="item.title_show"
                                :value="item.id">
                        </el-option>
                    </el-select>

                </el-form-item>

                <el-form-item label="排序" prop="list_order">
                    <el-input type="number"  v-model="currentEditData.list_order" ></el-input>
                </el-form-item>

                <el-form-item label="名称" prop="name">
                    <el-input v-model="currentEditData.name" placeholder="请输入名称" ></el-input>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input  type="textarea"
                               placeholder="请输入备注"
                               :rows="2"
                               v-model="currentEditData.remark">
                    </el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="currentEditData.status"
                               active-text="正常"
                               inactive-text="隐藏"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>

                <el-form-item label="权限" prop="rule" v-if="editDialog">
                    <el-tree
                            ref="edit-auth-tree"
                            :data="auth"
                            show-checkbox
                            :props="{label:'title'}"
                            node-key="id"
                            :default-expanded-keys="currentEditData.rule"
                            :default-checked-keys="currentEditData.rule"
                            @check-change="handleEditAuthCheckChange">
                    </el-tree>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="edit('edit-form')"  :loading="addLoading" >确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
    import utils  from "@/utils/function"
    const  { request } = utils

    export default {
        data() {

            let addRules = {
                parent_id:[
                    { required: true, message: '请选择组别', trigger: 'change' }
                ],
                list_order: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                rule:[
                    { required: true, message: '请选择权限', trigger: 'blur'  }
                ]
            }

            return {
                multipleSelection:[],           //列表中checkbox选中的值
                refreshLoading:false,   //刷新按钮加载动画
                addLoading:false,       //按钮加载动画
                treeList: [],           //列表数据
                addVisible: false,      //显示新增角色
                addFormInit:{},         //添加角色表单初始值
                form: {
                    list_order:50,
                    parent_id:'',
                    name:'',
                    rule:[],
                    remark:'',
                    status:0
                },
                auth:[],        //权限列表
                addRules : addRules,        //验证
                groupOptions: [],        //用户组列表
                currentEditData:{
                    id:0,
                    parent_id:0,
                    status:0,
                    list_order:0,
                    name:"",
                    remark:"",
                    rule:[]
                },     //当前编辑数据
                editDialog:false,        //编辑界面的显示
            }
        },

        methods: {
            handleEdit(index,row){                      //显示编辑界面
                request.loading().get('/system/auth/edit-role',{id:row.id}).then(response=>{
                    let {code,data:{checkedRules,role},msg} = response
                    if(code === 0){
                        let {id,parent_id,status,list_order,name,remark} = role
                        this.editDialog = true
                        this.currentEditData.id = id;
                        this.currentEditData.parent_id = parent_id;
                        this.currentEditData.status = status;
                        this.currentEditData.list_order = list_order;
                        this.currentEditData.name = name;
                        this.currentEditData.remark = remark;
                        this.$set(this.currentEditData,'rule',checkedRules)
                    }else {
                        this.$message.error(msg);
                    }
                })
            },
            handleEditAuthCheckChange(){    //编辑角色组权限的选择
                this.currentEditData.rule = []
                let res = this.$refs['edit-auth-tree'].getCheckedNodes(false,true)
                let arr = []
                res.forEach((item) => {
                    arr.push(item.id)
                })
                this.currentEditData.rule = arr
            },

            edit(form){             //编辑提交
                this.$refs[form].validate((valid) => {
                    if (!valid) {
                        console.log('error submit!!');
                        return false;
                    }
                    this.addLoading = true
                    //console.log(this.currentEditData)
                    request.post("/system/auth/edit-role",this.currentEditData).then(response=>{
                        this.addLoading = false
                        let {code,data,msg}  = response
                        if(code === 0 ){
                            this.$message.success(msg);
                            this.editDialog = false
                            this.getTreeList()
                            this.getRoleList()
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    });
                })
            },


            handleAddAuthCheckChange(){      //添加角色组权限的选择
                this.form.rule = []
                let res = this.$refs['add-auth-tree'].getCheckedNodes(false,true)
                let arr = []
                res.forEach((item) => {
                    arr.push(item.id)
                })
                this.form.rule = arr
            },
            refresh(){          //刷新
                this.refreshLoading = true
                this.getTreeList().then(response=>{
                    this.refreshLoading = false
                });
            },

            add(form) {       //新增角色提交
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.addLoading = true
                        request.post("/system/auth/add-role",this.form).then(response=>{
                            this.addLoading = false
                            let {code,data,msg}  = response
                            if(code === 0 ){
                                this.$message.success(msg);
                                this.addVisible = false;
                                this.resetAddForm()
                                this.getTreeList()
                                this.getRoleList()
                            } else {
                                this.$message.error(msg);
                            }
                        }).catch(error=>{
                            console.log(error);
                        });

                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetAddForm(){             //重置新增角色表单
                this.form = _.cloneDeep(this.addFormInit)
                this.$refs['add-auth-tree'].setCheckedKeys([]);
            },
            resetForm(formName){        //重置表单
                this.$refs[formName].resetFields();
            },
            delete(ids){           //删除
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(_.isNumber(ids)){
                        ids = [ids]
                    }
                    if(!_.isArray(ids)){
                        return false;
                    }
                    request.post("/system/auth/delete-role",{ids}).then(response=>{
                        console.log(response);
                        let {code,data,msg} = response
                        if(code === 0){
                            this.getTreeList()
                            this.getRoleList()
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }  else {
                            this.$message.error(msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    });

                }).catch((error) => {
                    console.log(error);
                    this.$message({
                        type: 'info',
                        message: '删除失败，请重试!'
                    });
                });
            },
            handleSelectionChange(val){                //列表checkbox选中事件
                this.multipleSelection = val;
            },
            handleDelete(index,row){            //删除一条
                this.delete(row.id);
            },
            allDelete(){                    //批量删除
                if(this.multipleSelection.length < 1){
                    this.$message.error('选择要删除的内容');
                    return false
                }
                this.delete(this.multipleSelection.map(value => value.id))
            },
            getTreeList(){              //获取角色列表树
                return request.loading().get("/system/auth/role-list").then(response=>{
                    let {code,data:{list},msg} = response
                    if(code === 0){

                        if(_.isArray(list) && list.length > 0){
                            this.treeList = list
                        } else {
                            this.treeList = []
                        }



                    } else {
                        this.$message.error(msg);
                    }
                    return response
                })
            },
            getRoleList(){          //获取角色列表
                request.get("/system/auth/add-user").then(response=>{
                    let {code,data:{roleList},msg} = response
                    if(code === 0){
                        this.groupOptions = roleList
                    } else {
                        this.$message.error(msg);
                    }
                }).catch(error=>{
                    console.log(error);
                });
            },

            getAuthList(){          //获取权限列表
                request.get("/system/auth/add-role").then(response=>{
                    //console.log(response)
                    let {code,data:{menuList},msg} = response
                    if(code === 0){
                        this.auth = menuList
                    } else {
                        this.$message.error(msg);
                    }

                }).catch(error=>{
                    console.log(error);
                });
            }

        },
        created:function(){
            this.getTreeList();
            this.getRoleList();
            this.getAuthList();
            this.addFormInit = _.cloneDeep(this.form)
        }
    };
</script>

<style>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
        padding-bottom: 10px;
    }

    .el-tree-node__content{padding:6px 0;}
</style>
